<template>
    <a-modal
            title="绘制电子围栏"
            :open="visible"
            width="800px"
            :maskClosable="false"
            @cancel="handleClose"
            :footer="null"
    >
        <div ref="mapContainer" style="height: 500px; width: 100%;"></div>
        <div style="margin-top: 16px; text-align: right;">
            <a-button class="btn" @click="createPolygon">新建</a-button>
            <a-button @click="handleClose" style="margin-left: 8px;">取消</a-button>
            <a-button type="primary" @click="handleSave" style="margin-left: 8px;">保存</a-button>
        </div>
    </a-modal>
</template>

<script setup>
    import { ref, watch, onMounted, nextTick } from 'vue';
    import AMapLoader from '@amap/amap-jsapi-loader';

    const props = defineProps({
        visible: Boolean,
        initialCoords: String,
    });

    const emits = defineEmits(['update:visible', 'save']);

    const mapContainer = ref(null);
    const map = ref(null);
    const polygon = ref(null);
    let polygonEditor = null;
    const pathArr = ref([]);
    const drawing = ref(false);

    // 当 prop.visible 变化时控制显示
    watch(() => props.visible, (val) => {
        if (val) {
            nextTick(() => {
                loadAmapScript().then(() => {
                    initMap();
                });
            });
        }
    }, { immediate: true });

    // 初始化地图
    function loadAmapScript() {
        return new Promise((resolve, reject) => {
            if (window.AMap) return resolve();
            const script = document.createElement('script');
            script.src = 'https://webapi.amap.com/maps?v=2.0&key=1d6104f9a8f549182c3c503e2a9d1270&plugin=AMap.PolygonEditor';
            script.onload = resolve;
            script.onerror = reject;
            document.head.appendChild(script);
        });
    }

    function initMap() {
        if (!mapContainer.value || !window.AMap) return;

        try {
            map.value = new AMap.Map(mapContainer.value, {
                zoom: 14,
                center: [116.397428, 39.90923],
            });

            polygon.value = new AMap.Polygon({
                path: [],
                strokeColor: '#00A3F5',
                strokeWeight: 3,
                fillColor: '#1791fc',
                fillOpacity: 0.4,
            });

            map.value.add(polygon.value);

            polygonEditor = new AMap.PolygonEditor(map.value, polygon.value);
            polygonEditor.open();

            map.value.on('click', (e) => {
                if (drawing.value) {
                    const lngLat = e.lnglat;
                    const path = polygon.value.getPath();
                    path.push(lngLat);
                    polygon.value.setPath(path);
                    pathArr.value.push([lngLat.lng, lngLat.lat]);
                    console.log('添加坐标点:', lngLat);
                }
            });
        } catch (e) {
            console.error('地图初始化失败:', e);
        }
    }

    function createPolygon() {
        try {
            if (polygonEditor) {
                polygonEditor.close();
                polygonEditor.setTarget();
                polygonEditor.open();
            }
            drawing.value = true;
        } catch (e) {
            console.error('创建多边形失败:', e);
        }
    }

    function handleSave() {
        try {
            if (!pathArr.value.length) {
                console.warn('多边形路径为空');
                return;
            }
            emits('save', JSON.stringify(pathArr.value));
            emits('update:visible', false);
        } catch (e) {
            console.error('保存失败:', e);
        }
    }

    function handleClose() {
        try {
            emits('update:visible', false);

            if (polygonEditor) {
                try {
                    polygonEditor.close();
                } catch (err) {
                    console.warn("polygonEditor 关闭异常：", err);
                }
                polygonEditor = null;
            }

            if (map.value) {
                try {
                    map.value.destroy();
                } catch (err) {
                    console.warn("map 销毁异常：", err);
                }
                map.value = null;
            }

            // 重置绘图状态
            pathArr.value = [];
            drawing.value = false;
        } catch (e) {
            console.error('关闭对话框失败:', e);
        }
    }

</script>

<style scoped>
    .btn {
        margin-right: 5px;
    }
</style>